__file__ = '2048.py'
__author__ = 'Jerry Liu'
__date__ = '2016-04-19'

import random

_totalscore =0
v = [[0, 0, 0, 0],
     [0, 0, 0, 0],
     [0, 0, 0, 0],
     [0, 0, 0, 0]]

def display(v, score):
    randomNum()
    print('{0:4} {1:4} {2:4} {3:4}'.format(v[0][0], v[0][1], v[0][2], v[0][3]))
    print('{0:4} {1:4} {2:4} {3:4}'.format(v[1][0], v[1][1], v[1][2], v[1][3]))
    print('{0:4} {1:4} {2:4} {3:4}'.format(v[2][0], v[2][1], v[2][2], v[2][3]))
    print('{0:4} {1:4} {2:4} {3:4}'.format(v[3][0], v[3][1], v[3][2], v[3][3]))
    print('Total score ', score)

#初始化
def init(v):
    '''
        随机分布网格值
    '''
    for i in range(4):
        v[i] = [random.choice([0, 0, 0, 2, 2, 4]) for x in v[i]]

# 删除0
def align(vList, direction):
    for i in range(vList.count(0)):
        vList.remove(0)
    zeros = [0 for x in range(4 - len(vList))]
    if direction == 'left':
        vList.extend(zeros)
    else:
        vList[:0] = zeros

# 随机2、4 添加到0的位置
def randomNum():
    count = getZeroCount()
    if count > 0:
        num = random.choice([2, 2, 2, 2, 4])
        # 随即一个位置
        ind = random.randrange(1, count+1)
        # 将这个位置的值设置新num
        n = 0
        for i in range(4):
            for j in range(4):
                if v[i][j] == 0:
                    n += 1
                    if n == ind:
                        v[i][j] = num
                        print(i, j, num)
                        return

# 计算零的个数
def getZeroCount():
    n = 0
    for q in v:
        n += q.count(0)
    return n

# 计算
def compute(vlist, direct):
    align(vlist, direct)
    addscore = 0
    if direct == 'left':
        for i in [0,1,2]:
            if vlist[i] == vlist[i+1] and vlist[i+1] != 0:
                vlist[i] *= 2
                vlist[i+1] = 0
                addscore += vlist[i]
    else:
        for i in [3, 2, 1]:
            if vlist[i] == vlist[i - 1] and vlist[i - 1] != 0:
                vlist[i] *= 2
                vlist[i - 1] = 0
                addscore += vlist[i]
    return addscore


# 左移
def left():
    _totalscore = 0
    for row in range(4):
        _totalscore += compute(v[row], 'left')

# 右移
def right():
    _totalscore = 0
    for row in range(4):
        _totalscore += compute(v[row], 'right')

# 上移
def up():
    _totalscore = 0
    for col in range(4):
        # 列转行，上为左
        vList = [v[row][col] for row in range(4)]
        _totalscore += compute(vList, 'left')
        # 从处理后的列表中的数字覆盖原来矩阵中的值
        for row in range(4):
            v[row][col] = vList[row]

# 下移
def down():
    _totalscore = 0
    for col in range(4):
        # 列转行，下为右
        vList = [v[row][col] for row in range(4)]
        _totalscore += compute(vList, 'right')
        # 从处理后的列表中的数字覆盖原来矩阵中的值
        for row in range(4):
            v[row][col] = vList[row]


def handler():
    direct = input('enter w a s d, ')
    if direct in ['W', 'w']:
        up()
    elif direct in ['S', 's']:
        down()
    elif direct in ['a', 'A']:
        left()
    elif direct in ['d', 'D']:
        right()
    else:
        print('命令错误。')

# 判断游戏是否结束
def isGameOver():

    if getZeroCount() > 0:
        return False
    else:
        # 判断是否可以移动
        for row in range(4):
            result = isListOver(v[row])
            if not result:
                return False

        for col in range(4):
            # 列转行，下为右
            vlist = [v[row][col] for row in range(4)]
            result = isListOver(vlist)
            if not result:
                return False
    return True

# 判断数据是否可以继续移动
def isListOver(vlist):
    for i in [0, 1, 2]:
        if vlist[i] == vlist[i + 1] and vlist[i + 1] != 0:
            return False
    return True

if __name__ == '__main__':
    display(v, 0)
    flag = isGameOver()
    while not flag:
        handler()
        display(v, _totalscore)
        flag = isGameOver()
    else:
        print('game over')